package com.qfedu.knowledge.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qfedu.knowledge.dao.RoleDao;
import com.qfedu.knowledge.dao.UserDao;
import com.qfedu.knowledge.entity.bo.RoleBO;
import com.qfedu.knowledge.entity.bo.UserBO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * @ClassName MyUserDetailServiceImpl
 * @Author ykx
 * @Date 2024/4/25 16:40
 * @Version 1.0
 */
@Service
public class MyUserDetailServiceImpl implements UserDetailsService {

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private UserDao userDao;

    @Autowired
    private RoleDao roleDao;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        QueryWrapper<UserBO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        UserBO userBO = userDao.selectOne(queryWrapper);

        if (Objects.isNull(userBO)) {
            throw new UsernameNotFoundException("用户名不存在");
        }

        RoleBO roleBO = roleDao.selectById(userBO.getRoleId());

        return new User(username, passwordEncoder.encode(userBO.getPassword()), AuthorityUtils.commaSeparatedStringToAuthorityList(roleBO.getRoleName()));
    }
}
